//
// Created by DengLibin on 2019/1/18 0018.
//

#include <iostream>
using  namespace std;
 struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};


/**
 * 反转链表 循环实现
 * @param headNode
 * @return
 */
ListNode * reverseListNode70(ListNode * headNode){
    if(headNode == NULL){
        return NULL;
    }
    //定义三个中间变量 当作滑动窗口
    ListNode * temp1 = NULL;
    ListNode * temp2 = headNode;
    ListNode * temp3 = temp2->next;
    while (true){
        temp2->next = temp1;
        temp1 = temp2;
        temp2 = temp3;
        if(temp2 == NULL){ //跳出循环
            break;
        }
        temp3 = temp3->next;
    }
    return temp1;
}
/**
  * 反转链表的m到n 循环实现
  * @param headNode
  * @return
  */
ListNode * reverseListNode(ListNode * headNode, int m, int n){
    if(headNode == NULL){
        return NULL;
    }
    int x = m;
    ListNode * preNode = NULL; //第一段尾
    ListNode * tempHeadNode = headNode; //第二段头节点
    while(x-1){
        preNode = tempHeadNode;
        if(tempHeadNode->next == NULL){//超出范围了
            return reverseListNode70(headNode);
        }
        tempHeadNode = tempHeadNode->next;
        x--;
    }
    ListNode * nextNode = NULL; //第三段头节点
    int y = n-m;
    ListNode * temp2Node = tempHeadNode;
    while(y){
        temp2Node = temp2Node->next;
        //判断是否到最后一个
        if(temp2Node->next == NULL){
            break;
        }
        y--;
    }
    nextNode = temp2Node->next;
    temp2Node->next = NULL;//打断
    ListNode * newHeadNode = reverseListNode70(tempHeadNode);//反转中间的链表
    //接上第一段和第三段
    if(preNode != NULL){
        preNode->next = newHeadNode;
    }
    tempHeadNode->next = nextNode; //反转后tempHeadNode变为第二段的尾节点

    if(m > 1){
        return headNode;
    }
    return  newHeadNode;

}
int main70(){
    ListNode l1(1);
    ListNode l2(2);
    ListNode l3(3);
    ListNode l4(4);
    ListNode l5(5);
    ListNode l6(6);
     l1.next = &l2;
     l2.next = &l3;
     l3.next = &l4;
     l4.next = &l5;
     l5.next = &l6;
    ListNode* head =  reverseListNode(&l1,7,9);
    ListNode * temp = head;
    while(temp != NULL){
        cout <<temp->val<<",";
        temp = temp->next;
    }
    return 0;
}

